package com.yuexun.dhdoctor.module.email.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.email.bean.MailFileDataBean;
import com.yuexun.dhdoctor.util.FileUtils;
import com.yuexun.dhdoctor.widget.HttpDownloader;

import org.kymjs.kjframe.ui.ViewInject;

import java.util.ArrayList;

/**
 * Created by work-jx on 2016/8/2.
 */
public class MailFileAdapter extends BaseAdapter {
    private static final String FILE_STATE_KEY = "fileState";   //查看下载状态键
    private static final String FILE_PATH_KEY = "filePath";   //文件路径键

    private Context mContext;
    private ArrayList<MailFileDataBean> beanList;
    boolean isDelete;

    public MailFileAdapter(Context mContext, ArrayList<MailFileDataBean> beanList, boolean isDelete) {
        this.mContext = mContext;
        this.beanList = beanList;
        this.isDelete = isDelete;
    }

    @Override
    public int getCount() {
        return null == beanList ? 0 : beanList.size();
    }

    @Override
    public Object getItem(int position) {
        return null == beanList ? null : beanList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (null == convertView) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_attachment, parent, false);
            holder = new ViewHolder();
            holder.filenameAndSizeT = (TextView) convertView.findViewById(R.id.tv_filename_and_fileSize);
            holder.downloadB = (Button) convertView.findViewById(R.id.btn_download);
            holder.btnLook = (TextView) convertView.findViewById(R.id.btn_look);
            holder.btnDelete = (ImageView) convertView.findViewById(R.id.btn_status);
            holder.progressBar = (ProgressBar) convertView.findViewById(R.id.progressBar);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        if (isDelete) {
            holder.downloadB.setVisibility(View.GONE);
            holder.btnDelete.setVisibility(View.VISIBLE);
            holder.btnLook.setVisibility(View.VISIBLE);
        } else {
            holder.downloadB.setVisibility(View.VISIBLE);
            holder.btnDelete.setVisibility(View.GONE);
            holder.btnLook.setVisibility(View.GONE);
        }

        final MailFileDataBean bean = beanList.get(position);
        SpannableStringBuilder styleStringBuilder = new SpannableStringBuilder(bean.getFileName() + "(" + new java.text.DecimalFormat("#.00").format(Double.valueOf(bean.getFileSize()) / 1024.00) + "KB)");
        styleStringBuilder.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.txt_black2)), 0, bean.getFileName().length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        holder.filenameAndSizeT.setText(styleStringBuilder);
        final FileUtils fileUtils = new FileUtils(mContext);
        final String[] filenames = bean.getFileName().split("\\.");
        if (fileUtils.isFileExist(AppConfig.FILE_CONTENT + bean.getFileUuid() + "." + filenames[filenames.length - 1])) {
            holder.downloadB.setText("查看");
        } else {
            holder.downloadB.setText("下载");
        }
        holder.downloadB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (!fileUtils.isFileExist(AppConfig.FILE_CONTENT + bean.getFileUuid() + "." + filenames[filenames.length - 1])) {
                            HttpDownloader httpDownLoader = new HttpDownloader(mContext);
                            holder.handler.sendEmptyMessage(0);
                            int result = httpDownLoader.downfile(AppConfig.WEB_FILE + bean.getFileUuid(),
                                    AppConfig.FILE_CONTENT, bean.getFileUuid() + "." + filenames[filenames.length - 1]);
                            if (result == 0) {
                                holder.handler.sendEmptyMessage(1);
                                Intent intent = fileUtils.openFile(FileUtils.getSDPATH() + AppConfig.FILE_CONTENT + bean.getFileUuid() + "." + filenames[filenames.length - 1]);
                                try {
                                    mContext.startActivity(intent);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else if (result == 1) {
                                Intent intent = fileUtils.openFile(FileUtils.getSDPATH() + AppConfig.FILE_CONTENT + bean.getFileUuid() + "." + filenames[filenames.length - 1]);
                                try {
                                    mContext.startActivity(intent);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else if (result == -1) {
                                holder.handler.sendEmptyMessage(2);
                            }
                        } else {
                            Intent intent = fileUtils.openFile(FileUtils.getSDPATH() + AppConfig.FILE_CONTENT + bean.getFileUuid() + "." + filenames[filenames.length - 1]);
                            try {
                                mContext.startActivity(intent);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();
            }
        });
        holder.btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                beanList.remove(position);
                notifyDataSetChanged();
            }
        });
        holder.btnLook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(bean.getFileUrl())) {
                    Intent intent = fileUtils.openFile(bean.getFileUrl());
                    try {
                        mContext.startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }else{
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            if (!fileUtils.isFileExist(AppConfig.FILE_CONTENT + bean.getFileUuid() + "." + filenames[filenames.length - 1])) {
                                HttpDownloader httpDownLoader = new HttpDownloader(mContext);
                                holder.handler.sendEmptyMessage(0);
                                int result = httpDownLoader.downfile(AppConfig.WEB_FILE + bean.getFileUuid(),
                                        AppConfig.FILE_CONTENT, bean.getFileUuid() + "." + filenames[filenames.length - 1]);
                                if (result == 0) {
                                    holder.handler.sendEmptyMessage(1);
                                    Intent intent = fileUtils.openFile(FileUtils.getSDPATH() + AppConfig.FILE_CONTENT + bean.getFileUuid() + "." + filenames[filenames.length - 1]);
                                    try {
                                        mContext.startActivity(intent);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                } else if (result == 1) {
                                    Intent intent = fileUtils.openFile(FileUtils.getSDPATH() + AppConfig.FILE_CONTENT + bean.getFileUuid() + "." + filenames[filenames.length - 1]);
                                    try {
                                        mContext.startActivity(intent);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                } else if (result == -1) {
                                    holder.handler.sendEmptyMessage(2);
                                }
                            } else {
                                Intent intent = fileUtils.openFile(FileUtils.getSDPATH() + AppConfig.FILE_CONTENT + bean.getFileUuid() + "." + filenames[filenames.length - 1]);
                                try {
                                    mContext.startActivity(intent);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }).start();
                }
            }
        });
        return convertView;
    }

//    Handler handler = new Handler() {
//
//        @Override
//        public void handleMessage(Message msg) {
//            switch (msg.what){
//                case 0:
//                    ViewInject.toast("开始下载...");
//                    break;
//                case 1:
//                    ViewInject.toast("下载完成");
//                    break;
//                case 2:
//                    ViewInject.toast("下载失败");
//                    break;
//            }
//        }
//
//    };

    class ViewHolder {
        public TextView filenameAndSizeT;
        public Button downloadB;
        public TextView btnLook;
        public ImageView btnDelete;
        public ProgressBar progressBar;

        Handler handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:
                        ViewInject.toast("开始下载...");
                        downloadB.setText("下载中");
                        break;
                    case 1:
                        ViewInject.toast("下载完成");
                        downloadB.setText("查看");
                        break;
                    case 2:
                        ViewInject.toast("下载失败");
                        downloadB.setText("下载");
                        break;
                }
            }

        };
    }

    private enum FileStateEnum {
        //0-未知 1-下载 2-查看
        UNKNOWN,
        DOWNLOAD,
        LOOK;

        public static FileStateEnum valueOf(int value) {
            if (value < 0 || value > values().length) {
                return getDefault();
            }

            return values()[value];
        }

        public static FileStateEnum getDefault() {
            return UNKNOWN;
        }
    }
}
